﻿@namespace Swimj.RazorLib.Partials
@typeparam T
@inherits ComponentBase

<RadzenTemplateForm Data="Model">
    @CreateFromItems()
</RadzenTemplateForm>

@code {

    RenderFragment CreateFromItems()
    {
        var type = typeof(T);
        var propertyInfos = type.GetProperties();

        return @<RadzenRow AlignItems="AlignItems.End">
        @foreach (var propertyInfo in propertyInfos)
        {
            var formColumnAttribute = propertyInfo.GetCustomAttribute<FormColumnAttribute>();
            if (formColumnAttribute != null)
            {
                <RadzenColumn Size="12" SizeSM="12" SizeLG="3">
                    @if (formColumnAttribute.GetControl().ControlType == ControlType.Text)
                    {
                        <RadzenFormField Text="@formColumnAttribute.DisplayText" Variant="@Variant.Outlined"
                                         Style="width: 100%;">
                            <RadzenTextBox Value="@(propertyInfo.GetValue(Model)?.ToString())"
                                           ValueChanged="@(v => ValueChangedHandle(propertyInfo, v))" />
                        </RadzenFormField>
                    }
                    else if (formColumnAttribute.GetControl().ControlType == ControlType.Select)
                    {
                        var control = (SelectControl)formColumnAttribute.GetControl();
                        if (control.SelectDataSource != null)
                        {
                            var instance = (ISelectDataSource?)Activator.CreateInstance(control.SelectDataSource);
                            if (instance != null)
                            {
                                var dataSource = instance.CreateDataSource();

                                <RadzenFormField Text="@formColumnAttribute.DisplayText" Variant="@Variant.Outlined"
                                                 Style="width: 100%;">
                                    <RadzenDropDown Data=@dataSource Value="@(propertyInfo.GetValue(Model))" TValue="object"
                                                    ValueChanged="@(v => ValueChangedHandle(propertyInfo, v))"
                                                    TextProperty="Value" ValueProperty="Key" />
                                </RadzenFormField>
                            }
                        }
                    }
                </RadzenColumn>
            }
        }


        <RadzenColumn Size="12" SizeSM="12" SizeLG="3">
            <RadzenButton Variant="Variant.Filled" Click=@(args => GridQueryButtonClick(args)) @onclick:stopPropagation="true">
                查询
            </RadzenButton>
            <RadzenButton Variant="Variant.Filled">
                重置
            </RadzenButton>
        </RadzenColumn>

    </RadzenRow>;
    }

    void ValueChangedHandle(PropertyInfo propertyInfo, object v)
    {
        propertyInfo.SetValue(Model, v);
    }

}